import Storage from './Storage';
import ZH_CN from '../lng/zh-CN';
import EN_US from '../lng/en-US';

const locales = {
    "en-US": EN_US,
    "zh-CN": ZH_CN,
};

class Intlga {
    constructor(props) {

    }

    init(lng) {
        Storage.setLocalObject("LNG", locales[lng]);
    }

    removeBlank(str) {
        var begin = false;
        var strs = str.split("");
        for (var i = 0; i < strs.length; i++) {
            if (strs[i] === "{") {
                begin = true;
            }
            if (strs[i] === "}") {
                begin = false;
            }
            if (begin && strs[i] === " ") {
                delete strs[i];  //只移除变量名里面的空格
            }
        }
        return strs.join("");
    }

    get(key, varibels) {
        var keys = [];
        if (key.indexOf(".") != -1) {
            keys = key.split(".");

            var locals = Storage.getLocalObject("LNG");
            locals ? locals : (() => {
                Storage.setLocalObject("LNG", ZH_CN);
                return ZH_CN;
            })();
            var result = undefined;
            for (var k in keys) {
                if (locals[keys[k]] === undefined) break;
                if (typeof locals[keys[k]] === "object") {
                    locals = locals[keys[k]];
                    continue;
                }
                result = locals[keys[k]];
            }
            if (result) {
                //去掉变量里面的空格
                result = this.removeBlank(result);
                if (varibels) {
                    for (var k in varibels) {
                        result = result.replace("{" + k + "}", varibels[k]);
                    }
                }
            }
            return result;
        }
    }
}

export default new Intlga();